<?php

namespace App\Services\Garage;

use App\Libs\Commons\MyException;
use App\Libs\Commons\MyMessage;
use App\Models\Fix\FactoryInfoModel;
use App\Models\Fix\FactoryModel;
use App\Models\Garage\AccountModel;
use Illuminate\Support\Facades\Redis;

class AccountService
{
    /**
     * 根据 token
     * 获取登录信息
     * @return array|mixed
     */
    public static function getLoginInfo()
    {
        $token = request()->header('token');
        if (!empty($token)) {
            $info = Redis::get($token);
            if (!empty($info)) {
                $info = json_decode($info, true);
            }
        }
        return $info ?? [];
    }

    /**
     * 获取token
     * @param array $param
     * @return string
     */
    public static function getToken($param = [])
    {
        $token = md5(time() . $param['mobile']);
        Redis::setex($token, 86400, json_encode($param, JSON_UNESCAPED_UNICODE));
        return $token;
    }

    /**
     * 登陆  根据手机号
     * @param array $param
     * @return mixed
     * @throws MyException
     */
    public static function login($param = [])
    {
        if (empty($param['mobile'])) {
            throw new \Exception("手机号不可为空", 0);
        }
        //获取用户信息
        $account = AccountModel::getInfo(['mobile' => $param['mobile'], 'deleted' => 0], 'id,role,mobile,realname');
        //不存在用户信息同步账号信息
        if (empty($account)) {
            throw new \Exception("账号不存在", 0);
        }

        $token = self::getToken($account);
        $account['token'] = $token;
        return $account;
    }

}
